<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/29
 * Time: 9:56
 * 拼多多接口
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\CommissionRebate;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use think\Db;
use think\Exception;

class Pdd extends Api{
	
	protected $noNeedRight = '*';
	
	
	/**
	 * 获取商品列表
	 * @param $keyword 关键字
	 * @param int $page 页数
	 */
	public function goodsList(){
		$keyword = input('post.keyword');
		$page = input('post.page', 1, 'int');
		$pageSize = input('post.page_size', 20, 'int');
		$sort = input('post.sort', 0, 'intval');
		$cid = input('post.cate_id', '', 'intval');
		
		$model = new \app\common\model\Pdd();
		$res = $model->goodsSearch($keyword, $page, $pageSize, $sort, '', '', '', $cid);
		if(isset($res['goods_search_response']['goods_list'])){
			$goods = [];
			$rebateModel = new CommissionRebate();
			$config = $rebateModel->where([
				'rebate_type' => $rebateModel::REBATE_TYPE_PDD
			])->find();
			foreach ($res['goods_search_response']['goods_list'] as $coupon) {
				$commissionAmount = 0;
				$couponAfterPrice = floatval(($coupon['min_normal_price']-$coupon['coupon_discount'])/100);
				if($config && $coupon['has_coupon']) {
					if($config['self_type'] == 1) {
						$commissionAmount = floor($coupon['promotion_rate']*$couponAfterPrice*$config['self']*10)/10000;
					} else {
						$commissionAmount = $config['self'];
					}
				}
				$goods[] = [
					'goods_img' => $coupon['goods_thumbnail_url'],
					'goods_title' => $coupon['goods_name'],
					'goods_id' => $coupon['goods_id'],
					'shop_title' => $coupon['mall_name'],
					'sale_number' => $coupon['sold_quantity'],
					'coupon_info' => '',
					'coupon_amount' => floatval($coupon['coupon_discount']/100),
					'coupon_after_price' => $couponAfterPrice,
					'coupon_remain_count' => $coupon['coupon_remain_quantity'],
					'coupon_total_count' => $coupon['coupon_total_quantity'],
					'goods_price' => floatval($coupon['min_normal_price']/100),
					'commission_amount' => floatval($commissionAmount),
					'commission_rate' => $coupon['promotion_rate'],
					'coupon_click_url' => '',
					'item_url' => 'https://mobile.yangkeduo.com/goods2.html?goods_id='.$coupon['goods_id'],
					'small_images' => [],
					'user_type' => 0,
					'goods_type' => 'pdd',
					'exchange_tips' => $coupon['has_coupon'] ? '确定使用抵扣券兑换该现金券吗？' : '',
					'isPinGou' => '',
					'planId' => '',
					'requestId' => '',
				];
			}
			$this->success('查询成功', $goods);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	
	/**
	 * 查询商品详情
	 */
	public function goodsDetail() {
		$goodsId = input('post.goods_id');
		!$goodsId && $this->error('商品ID不能为空');
		
		$model = new \app\common\model\Pdd();
		$res = $model->goodsDetail($goodsId);
		if(isset($res['goods_detail_response'])){
			$this->success('查询成功', $res['goods_detail_response']['goods_details'][0]);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
		
	}
	
	
	/**
	 * 生成推广位
	 * @param $number 生成数量
	 */
	public function generatePid(){
		$number = input('post.number', 1, 'int');
		$model = new \app\common\model\Pdd();
		$res = $model->generatePid($number);
		
		if(isset($res['p_id_generate_response'])){
			$this->success('生成成功', $res['p_id_generate_response']['p_id_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	
	/**
	 * 查询推广位
	 */
	public function queryPid(){
		$model = new \app\common\model\Pdd();
		$res = $model->queryPid();
		$this->success($res);
		
		if(isset($res['p_id_query_response'])){
			$this->success('生成成功', $res['p_id_query_response']['p_id_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	
	/**
	 * 生成推广链接
	 */
	public function generateUrl(){
		$goodsId = input('post.goods_id');
		!$goodsId && $this->error('商品ID不能为空', $goodsId);
		
		$pid = input('post.pid', '1718625_28499397');
		
		$model = new \app\common\model\Pdd();
		$res = $model->generateUrl($pid, $goodsId);
		
		if(isset($res['goods_promotion_url_generate_response'])){
			$this->success('生成成功', $res['goods_promotion_url_generate_response']['goods_promotion_url_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	/**
	 * 生成红包推广链接
	 */
	public function generatePromUrl(){
		$pid = input('post.pid');
		!$pid && $this->error('推广位不能为空');
		
		$pids = explode(',', str_replace('，', ',', $pid));
		foreach($pids as $k => $v){
			$pids[$k] = '"'.$v.'"';
		}
		
		$pid = implode(',', $pids);
		
		$model = new \app\common\model\Pdd();
		$res = $model->generatePromUrl($pid);
		$this->success($res);
		
		if(isset($res['goods_promotion_url_generate_response'])){
			$this->success('生成成功', $res['goods_promotion_url_generate_response']['goods_promotion_url_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	
	/**
	 * 生成优惠券
	 * @param $goodsId
	 * @param $amount
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function exchange($goodsId, $amount){
		!$goodsId && $this->error('商品ID不能为空');
		
		$pid = input('post.pid', '1718625_28499397');
		
		
		$model = new \app\common\model\Pdd();
		
		//扣除券金额
		$userId = $this->auth->id;
		$user = Db::name('user')->find($userId);
		if($amount > 0 && $user['voucher_balance'] < $amount) {
			$this->error('抵扣券不足，当前抵扣券【'.$user['voucher_balance'].'】');
		}
		
		Db::startTrans();
		try {
			if($amount > 0) {
				$userRes = Db::name('user')->where(['id' => $userId])->setDec('voucher_balance', $amount);
				if(!$userRes) {
					throw new Exception('扣除抵扣券出错');
				}
				
				//记录资金流水
				$logModel = new FundsRecord();
				$logRes = $logModel->addRecord($userId, $amount, $user['voucher_balance'], $logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_PDD);
				if(!$logRes) {
					throw new Exception('记录资金流水出错');
				}
			}
			
			//添加用户领券记录
			$recordRes = Db::name('CouponCollectRecord')
				->insert([
					'user_id' => $userId,
					'goods_id' => $goodsId,
					'type' => CouponCollectRecord::TYPE_PDD,
					'create_time' => time()
				]);
			if(!$recordRes) {
				throw new Exception('添加领取记录出错');
			}
			
			
			//生成推广链接
			$res = $model->generateUrl($pid, $goodsId, $this->auth->id);
			
			if(!isset($res['goods_promotion_url_generate_response'])){
				throw new Exception($res['error_response']['error_msg']);
			}
			
			Db::commit();
			return [
				'status' => true,
				'info' => $res['goods_promotion_url_generate_response']['goods_promotion_url_list'][0]
			];
			
		} catch (Exception $e) {
			Db::rollback();
			return [
				'status' => false,
				'info' => $e->getMessage()
			];
		}
		
		
	}
	
	
	/**
	 * 生成推广链接
	 */
	public function weappQrcodeUrlGen(){
		$goodsId = input('post.goods_id');
		!$goodsId && $this->error('商品ID不能为空', $goodsId);
		
		$pid = input('post.pid', '1718625_28499397');
		
		$model = new \app\common\model\Pdd();
		$res = $model->weappQrcodeUrlGen($pid, $goodsId);
		$this->success($res);
		
		if(isset($res['goods_promotion_url_generate_response'])){
			$this->success('生成成功', $res['goods_promotion_url_generate_response']['goods_promotion_url_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
	
	
	/**
	 * 获取分类
	 */
	public function goodsCatsGet(){
		$pid = input('post.pid', 0, 'intval');
		$model = new \app\common\model\Pdd();
		$res = $model->goodsCatsGet($pid);
		if(isset($res['goods_cats_get_response'])){
			$this->success('查询成功'.$pid, $res['goods_cats_get_response']['goods_cats_list']);
		} elseif (isset($res['error_response'])) {
			$this->error($res['error_response']['error_msg']);
		}
	}
}